如何从 Python 中的字符串中删除前导和尾随空格?
例如:
" Hello " --> "Hello" " Hello" --> "Hello" "Hello " --> "Hello" "Bob has a cat" --> "Bob has a cat"
只是一个空格还是所有连续的空格?如果是第二个,那么字符串已经有一个.strip()方法:
.strip()
>>> ' Hello '.strip() 'Hello' >>> ' Hello'.strip() 'Hello' >>> 'Bob has a cat'.strip() 'Bob has a cat' >>> ' Hello '.strip() # ALL consecutive spaces at both ends removed 'Hello'
但是,如果您只需要删除一个空格,您可以这样做:
def strip_one_space(s): if s.endswith(" "): s = s[:-1] if s.startswith(" "): s = s[1:] return s >>> strip_one_space(" Hello ") ' Hello'
另外,请注意,它str.strip()也会删除其他空白字符(例如制表符和换行符)。要仅删除空格,您可以将要删除的字符指定为 的参数strip,即:
str.strip()
strip
>>> " Hello\n".strip(" ") 'Hello\n'